package jnpf.property.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.service.IBaseSerialNumberService;
import jnpf.model.visiual.superQuery.ConditionJsonModel;
import jnpf.model.visiual.superQuery.SuperQueryConditionModel;
import jnpf.model.visiual.superQuery.SuperQueryJsonModel;
import jnpf.permission.entity.UserEntity;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.permission.service.AuthorizeService;
import jnpf.property.entity.ZcglPropertyMeterEntity;
import jnpf.property.mapper.ZcglPropertyMeterMapper;
import jnpf.property.model.zcglpropertymeter.ZcglPropertyMeterForm;
import jnpf.property.model.zcglpropertymeter.ZcglPropertyMeterPagination;
import jnpf.property.service.ZcglPropertyMeterService;
import jnpf.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * zcglPropertyMeter
 * 版本： V3.2.0
 * 版权： 智果云科技（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2024-12-03
 */
@Service
public class ZcglPropertyMeterServiceImpl extends ServiceImpl<ZcglPropertyMeterMapper, ZcglPropertyMeterEntity> implements ZcglPropertyMeterService {


    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    private IBaseSerialNumberService iBaseSerialNumberService;


    @Override
    public List<ZcglPropertyMeterEntity> getList(ZcglPropertyMeterPagination zcglPropertyMeterPagination) {
        return getTypeList(zcglPropertyMeterPagination, zcglPropertyMeterPagination.getDataType());
    }

    @Override
    public List<ZcglPropertyMeterEntity> getTypeList(ZcglPropertyMeterPagination zcglPropertyMeterPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        int total = 0;
        int zcglPropertyMeterNum = 0;
        QueryWrapper<ZcglPropertyMeterEntity> zcglPropertyMeterQueryWrapper = new QueryWrapper<>();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(zcglPropertyMeterPagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(zcglPropertyMeterPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
            for (ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null) {
                    if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                        conditionjson.setFieldValue("[]");
                    }
                }
                conditionjson.setTableName(tableName);
            }
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();
            int zcglPropertyMeterNum1 = 0;
            QueryWrapper<ZcglPropertyMeterEntity> zcglPropertyMeterSuperWrapper = new QueryWrapper<>();
            zcglPropertyMeterNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcglPropertyMeterSuperWrapper, superQueryList, matchLogic, "zcglPropertyMeter")
                    , new ZcglPropertyMeterEntity(), zcglPropertyMeterNum1);
            if (zcglPropertyMeterNum1 > 0) {
                List<String> zcglPropertyMeterList = this.list(zcglPropertyMeterSuperWrapper).stream().map(ZcglPropertyMeterEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(zcglPropertyMeterList);
                intersectionSuperList.add(zcglPropertyMeterList);
            }
            superOp = matchLogic;
            //and or
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object zcglPropertyMeterObj = authorizeService.getCondition(new AuthorizeConditionModel(zcglPropertyMeterQueryWrapper, zcglPropertyMeterPagination.getMenuId(), "zcgl_property_meter"));
                if (ObjectUtil.isEmpty(zcglPropertyMeterObj)) {
                    return new ArrayList<>();
                } else {
                    zcglPropertyMeterQueryWrapper = (QueryWrapper<ZcglPropertyMeterEntity>) zcglPropertyMeterObj;
                    zcglPropertyMeterNum++;
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object zcglPropertyMeterObj = authorizeService.getCondition(new AuthorizeConditionModel(zcglPropertyMeterQueryWrapper, zcglPropertyMeterPagination.getMenuId(), "zcglPropertyMeter"));
                if (ObjectUtil.isEmpty(zcglPropertyMeterObj)) {
                    return new ArrayList<>();
                } else {
                    zcglPropertyMeterQueryWrapper = (QueryWrapper<ZcglPropertyMeterEntity>) zcglPropertyMeterObj;
                    zcglPropertyMeterNum++;
                }


            }
        }
        if (isPc) {
            if (ObjectUtil.isNotEmpty(zcglPropertyMeterPagination.getProject())) {
                zcglPropertyMeterNum++;
                zcglPropertyMeterQueryWrapper.lambda().eq(ZcglPropertyMeterEntity::getProject, zcglPropertyMeterPagination.getProject());
            }

            if (ObjectUtil.isNotEmpty(zcglPropertyMeterPagination.getZcId())) {
                zcglPropertyMeterNum++;
                zcglPropertyMeterQueryWrapper.lambda().eq(ZcglPropertyMeterEntity::getZcId, zcglPropertyMeterPagination.getZcId());
            }

            if (ObjectUtil.isNotEmpty(zcglPropertyMeterPagination.getEquipmentName())) {
                zcglPropertyMeterNum++;
                zcglPropertyMeterQueryWrapper.lambda().eq(ZcglPropertyMeterEntity::getEquipmentName, zcglPropertyMeterPagination.getEquipmentName());
            }

        }
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            zcglPropertyMeterQueryWrapper.lambda().in(ZcglPropertyMeterEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            zcglPropertyMeterQueryWrapper.lambda().and(t -> t.in(ZcglPropertyMeterEntity::getId, finalAllSuperIDlist));
        }

        //排序
        if (StringUtil.isEmpty(zcglPropertyMeterPagination.getSidx())) {
            zcglPropertyMeterQueryWrapper.lambda().orderByDesc(ZcglPropertyMeterEntity::getId);
        } else {
            try {
                String sidx = zcglPropertyMeterPagination.getSidx();
                ZcglPropertyMeterEntity zcglPropertyMeterEntity = new ZcglPropertyMeterEntity();
                Field declaredField = zcglPropertyMeterEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                zcglPropertyMeterQueryWrapper = "asc".equals(zcglPropertyMeterPagination.getSort().toLowerCase()) ? zcglPropertyMeterQueryWrapper.orderByAsc(value) : zcglPropertyMeterQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<ZcglPropertyMeterEntity> page = new Page<>(zcglPropertyMeterPagination.getCurrentPage(), zcglPropertyMeterPagination.getPageSize());
                IPage<ZcglPropertyMeterEntity> userIPage = this.page(page, zcglPropertyMeterQueryWrapper);
                return zcglPropertyMeterPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<ZcglPropertyMeterEntity> list = new ArrayList();
                return zcglPropertyMeterPagination.setData(list, list.size());
            }
        } else {
            return this.list(zcglPropertyMeterQueryWrapper);
        }
    }


    @Override
    public ZcglPropertyMeterEntity getInfo(String id) {
        QueryWrapper<ZcglPropertyMeterEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcglPropertyMeterEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ZcglPropertyMeterEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, ZcglPropertyMeterEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(ZcglPropertyMeterEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法


    //验证表单唯一字段
    @Override
    public boolean checkForm(ZcglPropertyMeterForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        if (isUp) {
            id = form.getId();
        }
        if (total > 0) {
            return true;
        }
        return false;
    }

    @Override
    public ActionResult saveMeter(ZcglPropertyMeterForm zcglPropertyMeterForm) {

        /*
        * 抄表录入逻辑
        *   1.抄录之后生成账单
        *   2.计算费用规则:
        *       2.1:用量*倍率*单价等于费用
        *       2.2:本期读数减去上期读数就是用量
        * */

        boolean b = this.checkForm(zcglPropertyMeterForm, 0);
        if (b) {
            return ActionResult.fail("单行输入不能重复");
        }
        String mainId = RandomUtil.uuId();

        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        ZcglPropertyMeterEntity entity = JsonUtil.getJsonToBean(zcglPropertyMeterForm, ZcglPropertyMeterEntity.class);
        entity.setId(mainId);
        entity.setCopyNumber(iBaseSerialNumberService.getSerialNumber("E", 7));

        return ActionResult.success("抄录成功");
    }


}
